How can I be certain that my code is flawless? [duplicate]

Posted by David on Programmers See other posts from Programmers or by David
Published on 2014-06-02T13:50:26Z Indexed on 2014/06/02 21:45 UTC
Read the original article Hit count: 226

Filed under:

This question already has an answer here:

I have just completed an exercise from my textbook which wanted me to write a program to check if a number is prime or not.

I have tested it and seems to work fine, but how can I be certain that it will work for every prime number?

public boolean isPrime(int n)
    {
       int divisor = 2;
       int limit = n-1 ; 

            if (n == 2)
            {                  
                return true;
            }
            else
            {
                int mod = 0;
                while (divisor <= limit)
                {
                      mod = n % divisor;
                      if (mod == 0)
                      {
                          return false;
                      }
                    divisor++;
                }

                if (mod > 0)
                {
                    return true;
                }
            }

      return false;
}

Note that this question is not a duplicate of Theoretically Bug Free Programs because that question asks about whether one can write bug free programs in the face of the the limitative results such as Turing's proof of the incomputability of halting, Rice's theorem and Godel's incompleteness theorems. This question asks how a program can be shown to be bug free.

© Programmers or respective owner

Related posts about java